package com.shop.lock;

import java.util.concurrent.TimeUnit;

/**
 * 1、死锁肯定是两个或两个以上的线程之间，单线程肯定不会发生死锁
 * 2、需要自己持有锁再抢占另一个锁，（吃着碗里看着锅里）
 */

class HoldLock implements Runnable{

    private String lockA ;

    private String lockB ;

    public HoldLock(String lockA,String lockB){
        this.lockA = lockA;
        this.lockB = lockB ;
    }

    @Override
    public void run() {
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName()+"\t 持有"+lockA+" 尝试获得："+lockB);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (lockB){
                System.out.println(Thread.currentThread().getName()+"\t 持有"+lockB+" 尝试获得"+lockA);
            }
        }
    }
}
public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";

        new Thread(new HoldLock(lockA,lockB),"threadAAA").start();
        new Thread(new HoldLock(lockB,lockA),"threadBBB").start();
    }
}
